<template>
  <div class="h-full flex flex-col">
    <div class="p-4 border-b border-gray-700/50">
      <h2 class="text-xs font-semibold text-gray-400 uppercase tracking-wider px-2 mb-3">历史对话</h2>
      <div class="flex justify-between">
        <button 
          class="px-4 py-2 flex items-center justify-center gap-2 text-sm font-medium text-blue-500 hover:text-blue-400 transition-colors duration-200"
          @click="refreshHistory"
          :disabled="isLoading"
          title="刷新历史记录"
        >
          <i class="fa fa-refresh"></i> 刷新
        </button>
        <button 
          class="px-4 py-2 flex items-center justify-center gap-2 text-sm font-medium text-red-500 hover:text-red-400 transition-colors duration-200"
          @click="clearAllHistory"
          :disabled="isLoading || historySessions.length === 0"
          title="清空所有历史记录"
        >
          <i class="fa fa-trash"></i> 清空历史
        </button>
      </div>
    </div>

    <div class="flex-1 overflow-y-auto">
      <!-- 历史会话列表 -->
      <div v-if="!isLoading && historySessions.length > 0" class="px-4 py-3 space-y-2">
        <div v-for="session in historySessions" :key="session.convId" 
             @click="openSession(session)" 
             class="p-3 rounded-xl hover:bg-gray-800/70 cursor-pointer transition-all transform duration-300 hover:translate-x-1 hover:shadow-sm border border-transparent hover:border-blue-500/50 magic-hover">
          <div class="flex items-center justify-between mb-2">
            <div class="flex items-center space-x-2.5">
              <div v-if="session.characterAvatar" class="w-7 h-7 rounded-full flex items-center justify-center shadow-sm overflow-hidden">
                <img :src="session.characterAvatar" :alt="session.characterName" class="w-full h-full object-cover">
              </div>
              <div v-else class="w-7 h-7 rounded-full flex items-center justify-center shadow-sm" :style="{ backgroundColor: generateColorFromText(session.characterName || 'Unknown') }">
                <span class="text-white font-medium text-xs">{{ session.characterName?.charAt(0) || '?' }}</span>
              </div>
              <h3 class="font-medium text-gray-200 text-sm">{{ session.characterName || '未知角色' }}</h3>
            </div>
            <span class="text-xs text-gray-500">{{ formatSessionTime(session.lastUpdateTime || Date.now()) }}</span>
          </div>
          <p class="text-gray-400 text-xs line-clamp-1">{{ session.title || session.lastMessage || '无消息内容' }}</p>
          <div class="flex items-center justify-between mt-2">
            <span class="text-xs text-gray-500">{{ session.messageCount || 0 }}条消息</span>
            <button 
              @click.stop="deleteSessionById(session.convId)" 
              class="text-xs text-red-500 hover:text-red-400 transition-colors duration-200 p-1 hover:bg-red-500/10 rounded"
              title="删除会话"
            >
              <i class="fa fa-trash-o"></i>
            </button>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-else-if="!isLoading" class="h-full flex flex-col items-center justify-center p-8 text-center">
        <div class="w-20 h-20 rounded-full bg-blue-600/30 flex items-center justify-center mb-6 border border-blue-500/50 animate-float">
          <i class="fa fa-history text-blue-500 text-3xl"></i>
        </div>
        <h3 class="text-lg font-medium gradient-text mb-3">暂无历史记录</h3>
        <p class="text-gray-500 text-sm max-w-xs">开始与角色对话后，这里将显示您的历史会话记录</p>
      </div>

      <!-- 加载状态 -->
      <div v-if="isLoading" class="p-8 flex flex-col items-center justify-center">
        <div class="w-10 h-10 border-4 border-blue-500 border-t-transparent rounded-full animate-spin mb-4"></div>
        <p class="text-gray-400 text-sm">加载中...</p>
      </div>
    </div>

    <!-- 分页控件 -->
    <div class="p-4 border-t border-gray-700/50" v-if="!isLoading && pagination.totalElements > pagination.size">
      <div class="flex justify-center items-center space-x-4">
        <button 
          @click="handleCurrentChange(pagination.page)"
          :disabled="pagination.page <= 0"
          class="p-2 rounded-full text-gray-400 hover:text-white hover:bg-gray-800/50 transition-all duration-300"
        >
          <i class="fa fa-chevron-left"></i>
        </button>
        <span class="text-sm text-gray-400">
          第 {{ pagination.page + 1 }} / {{ pagination.totalPages + 1 }} 页
        </span>
        <button 
          @click="handleCurrentChange(pagination.page + 2)"
          :disabled="pagination.page >= pagination.totalPages"
          class="p-2 rounded-full text-gray-400 hover:text-white hover:bg-gray-800/50 transition-all duration-300"
        >
          <i class="fa fa-chevron-right"></i>
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { getHistorySessions, deleteSession } from '../api/roleApi';
import { generateColorFromText } from '../utils/index.js';

export default {
  name: 'HistoryList',
  props: {
    userId: {
      type: Number,
      required: true
    }
  },
  emits: ['session-selected'],
  setup(props, { emit }) {
    const historySessions = ref([]);
    const isLoading = ref(false);
    const pagination = ref({
      page: 0,
      size: 20,
      totalElements: 0,
      totalPages: 0
    });
    
    // 加载历史记录
    const loadHistorySessions = async () => {
      try {
        isLoading.value = true;
        const response = await getHistorySessions(
          props.userId, 
          pagination.value.page, 
          pagination.value.size
        );
        
        if (response.code === 200) {
          historySessions.value = response.data.content || [];
          pagination.value = {
            page: response.data.page,
            size: response.data.size,
            totalElements: response.data.totalElements,
            totalPages: response.data.totalPages
          };
        } else {
          console.error('加载历史记录失败:', response.message);
          // 使用模拟数据
          loadMockData();
        }
      } catch (error) {
        console.error('加载历史记录失败:', error);
        // 使用模拟数据
        loadMockData();
      } finally {
        isLoading.value = false;
      }
    };
    
    // 加载模拟数据
    const loadMockData = () => {
      // 模拟历史会话数据
      const mockSessions = [
        {
          convId: 'mock-1',
          charId: 1001,
          characterName: '李白',
          title: '诗歌交流',
          lastMessage: '举头望明月，低头思故乡。这首诗表达了游子思乡之情...',
          lastUpdateTime: new Date().getTime() - 3600000, // 1小时前
          messageCount: 12
        },
        {
          convId: 'mock-2',
          charId: 1002,
          characterName: '爱因斯坦',
          title: '相对论探讨',
          lastMessage: '相对论的核心思想是时间和空间是相对的，而非绝对的...',
          lastUpdateTime: new Date().getTime() - 86400000, // 1天前
          messageCount: 8
        },
        {
          convId: 'mock-3',
          charId: 1003,
          characterName: '诸葛亮',
          title: '智慧对话',
          lastMessage: '夫君子之行，静以修身，俭以养德...',
          lastUpdateTime: new Date().getTime() - 172800000, // 2天前
          messageCount: 15
        }
      ];
      
      historySessions.value = mockSessions;
      pagination.value = {
        page: 0,
        size: 20,
        totalElements: mockSessions.length,
        totalPages: 0
      };
    };
    
    // 刷新历史记录
    const refreshHistory = () => {
      pagination.value.page = 0;
      loadHistorySessions();
    };
    
    // 打开会话
    const openSession = (session) => {
      emit('session-selected', session);
    };
    
    // 删除会话 - 重命名函数避免与API函数名冲突
    const deleteSessionById = async (convId) => {
      try {
        const confirmed = confirm('确定要删除这条会话记录吗？');
        if (!confirmed) return;
        
        const response = await deleteSession(convId);
        if (response.code === 200) {
          // 从列表中移除该会话，避免重新加载
          historySessions.value = historySessions.value.filter(s => s.convId !== convId);
          // 更新分页信息
          pagination.value.totalElements--;
        } else {
          console.error('删除会话记录失败:', response.message);
          alert('删除会话记录失败');
        }
      } catch (error) {
        console.error('删除会话记录失败:', error);
        alert('删除会话记录失败');
      }
    };
    
    // 清空所有历史记录
    const clearAllHistory = async () => {
      try {
        const confirmed = confirm('确定要清空所有历史记录吗？此操作不可恢复。');
        if (!confirmed) return;
        
        // 在实际项目中，这里应该调用后端的批量删除接口
        // 现在我们只在前端清空
        historySessions.value = [];
        pagination.value.totalElements = 0;
        
        alert('所有历史记录已清空');
      } catch (error) {
        console.error('清空历史记录失败:', error);
        alert('清空历史记录失败');
      }
    };
    
    // 处理页面大小变化
    const handleSizeChange = (size) => {
      pagination.value.size = size;
      pagination.value.page = 0;
      loadHistorySessions();
    };
    
    // 处理当前页变化
    const handleCurrentChange = (current) => {
      pagination.value.page = current - 1;
      loadHistorySessions();
    };
    
    // 格式化会话时间
    const formatSessionTime = (timestamp) => {
      if (!timestamp) return '';
      const date = new Date(timestamp);
      const now = new Date();
      const diffDays = Math.floor((now - date) / (1000 * 60 * 60 * 24));
      
      if (diffDays === 0) {
        return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
      } else if (diffDays === 1) {
        return '昨天 ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
      } else if (diffDays < 7) {
        return diffDays + '天前';
      } else {
        return date.toLocaleDateString('zh-CN');
      }
    };
    
    // 组件挂载时加载历史记录
    onMounted(() => {
      loadHistorySessions();
    });
    
    return {
      historySessions,
      isLoading,
      pagination,
      loadHistorySessions,
      refreshHistory,
      openSession,
      deleteSessionById,
      clearAllHistory,
      handleSizeChange,
      handleCurrentChange,
      formatSessionTime,
      generateColorFromText
    };
  }
};
</script>

<style scoped>
/* 自定义动画 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes float {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-10px);
  }
}

.animate-fadeIn {
  animation: fadeIn 0.3s ease-out;
}

.animate-float {
  animation: float 6s ease-in-out infinite;
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 8px;
}

::-webkit-scrollbar-track {
  background: rgba(30, 30, 30, 0.5);
}

::-webkit-scrollbar-thumb {
  background: #6b7280;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: #4b5563;
}

/* 加载动画 */
@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.animate-spin {
  animation: spin 1s linear infinite;
}

/* 魔法效果 */
.magic-hover {
  transition: all 0.3s ease;
}

.magic-hover:hover {
  transform: translateY(-5px);
}

/* 渐变文字 */
.gradient-text {
  background: linear-gradient(45deg, #00A3FF, #00FF9D, #BF00FF);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  background-size: 200% 200%;
  animation: gradientShift 5s ease infinite;
}

@keyframes gradientShift {
  0% { background-position: 0% 50%; }
  50% { background-position: 100% 50%; }
  100% { background-position: 0% 50%; }
}

/* 玻璃效果 */
.glass {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}
</style>